package com.example.choupaiapp.main.activity.mine;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.DialogUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.bean.JobListBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.view.MyWheelView;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.example.choupaiapp.common.util.DateFormatUtil.getTime;

/**
 * Created by ASUS on 2019/10/31.
 */

public class MineInfoActivity extends CommonActivity {


    @BindView(R.id.right_tv)
    TextView right_tv;
    @BindView(R.id.nickname)
    EditText nickname;
    @BindView(R.id.change_num)
    TextView changeNum;
    @BindView(R.id.sex)
    TextView sex;
    @BindView(R.id.birthday)
    TextView birthday;
    @BindView(R.id.age)
    TextView age;
    @BindView(R.id.job)
    TextView job;
    @BindView(R.id.area)
    TextView area;
    private UserInfoBean userInfoBean;
    private String name;
    private UserInfoBean mUserInfoBean;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_info);
    }

    @Override
    protected void initView() {
        setTitle("编辑个人信息");
//        right_tv.setText("提交");

        mUserInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");

        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                if (!TextUtils.isEmpty(name) && !name.equals(nickname.getText().toString().trim())) {
                    if (!TextUtils.isEmpty(nickname.getText().toString().trim())) {
                        showDialog(context, "修改中...");
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("nickname", nickname.getText().toString().trim());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_USERINFO, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                            @Override
                            public void onSuccess(SendCodeBean sendCodeBean) {
                                dismissDialog();
                                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                    mUserInfoBean.getUser().setNickname(nickname.getText().toString().trim());
                                    SharedPreferencesHelp.putBean("userInfo", mUserInfoBean);
                                    EventBus.getDefault().post("refresh_mimeAll_list");
                                    EventBus.getDefault().post("refresh_mine");
                                    finishActivity();
                                } else {
                                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                    } else {
                                        showImageToas(sendCodeBean.getMsg());
                                    }
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                dismissDialog();
                            }
                        });
                    } else {
                        showImageToas("请填写昵称");
                    }
                } else {
                    MineInfoActivity.super.onBackPressed();
                }
            }
        });

        userInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");

        changeNum.setText("今年还可修改" + userInfoBean.getCountUpdateName() + "次");
    }

    @Override
    protected void initData() {
        name = userInfoBean.getUser().getNickname();

        nickname.setText(userInfoBean.getUser().getNickname());

        if (userInfoBean.getUser().getSex() == 1) {
            sex.setText("男");
        } else if (userInfoBean.getUser().getSex() == 2) {
            sex.setText("女");
        } else {
            sex.setText("未知");
        }

        age.setText(userInfoBean.getUser().getAge() == null ? "" : userInfoBean.getUser().getAge());
        job.setText(userInfoBean.getUser().getOccupation() == null ? "" : userInfoBean.getUser().getOccupation());

        area.setText(userInfoBean.getUser().getAddress());

    }


    private void showTimePick() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        //正确设置方式 原因：注意事项有说明
        startDate.set(1900, 0, 1);
        endDate.set(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DATE));

        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                showDialog(context, "修改中...");
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("birthday", getTime(date));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_USERINFO, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                    @Override
                    public void onSuccess(SendCodeBean sendCodeBean) {
                        dismissDialog();
                        if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                            EventBus.getDefault().post("refresh_mine");
                            birthday.setText(getTime(date));
                        } else {
                            if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                            } else {
                                showImageToas(sendCodeBean.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentTextSize(20)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setItemVisibleCount(5)
                .setTextColorCenter(Color.parseColor("#ff282828"))
                .setTextColorOut(Color.parseColor("#cccccc"))
//                        .setTitleText("Title")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
//                        .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.parseColor("#ffffcc33"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#ffffcc33"))//取消按钮文字颜色
                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setBgColor(Color.WHITE)//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .setGravity(Gravity.CENTER)
                .setLineSpacingMultiplier(2)
                .build();
        pvTime.show();
    }


    //    @Override
    @OnClick({R.id.sex_rl, R.id.birthday_rl, R.id.interest_rl, R.id.area_rl, R.id.age_rl, R.id.job_rl/*,R.id.right_tv*/})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.sex_rl:
                List<String> list = new ArrayList<>();
                list.add("男");
                list.add("女");
                OptionsPickerView optionsPickerView = new OptionsPickerBuilder(context, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {

                        showDialog(context, "修改中...");
                        JSONObject jsonObject = new JSONObject();
                        try {
                            if (options1 == 0) {
                                jsonObject.put("sex", 1);
                            } else {
                                jsonObject.put("sex", 2);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_USERINFO, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                            @Override
                            public void onSuccess(SendCodeBean sendCodeBean) {
                                dismissDialog();
                                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                    EventBus.getDefault().post("refresh_mine");
                                    sex.setText(list.get(options1));
                                } else {
                                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                    } else {
                                        showImageToas(sendCodeBean.getMsg());
                                    }
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                dismissDialog();
                            }
                        });
                    }
                })
                        .setCancelText("取消")
                        .setSubmitText("确定")
                        .setSubCalSize(18)
                        .setSubmitColor(Color.parseColor("#ffffcc33"))//确定按钮文字颜色
                        .setCancelColor(Color.parseColor("#ffffcc33"))//取消按钮文字颜色
                        .setContentTextSize(20)//滚轮文字大小
                        .setCyclic(false, false, false)//循环与否
                        .setOutSideCancelable(false)//点击外部dismiss default true
                        .build();

                optionsPickerView.setPicker(list);
                optionsPickerView.show();
                break;
            case R.id.birthday_rl:
                showTimePick();
                break;
            case R.id.interest_rl:
                startActivity(InterestLabelActivity.class);
                break;
            case R.id.area_rl:
                break;
            case R.id.age_rl:
                DialogUtil.getInstance().showBottomDialog(context, R.layout.dialog_info_age);
                LinearLayout dialog_info_age = (LinearLayout) DialogUtil.getInstance().dialog_bottom_layout;

                List<String> ageList = new ArrayList<>();
                ageList.add("50后");
                ageList.add("60后");
                ageList.add("70后");
                ageList.add("80后");
                ageList.add("90后");
                ageList.add("00后");
                MyWheelView age_wheel = dialog_info_age.findViewById(R.id.age_wheel);
                age_wheel.setCyclic(false);
                age_wheel.setTextSize(21);
                age_wheel.setItemsVisibleCount(5);
                age_wheel.setLineSpacingMultiplier(2);
                age_wheel.setAdapter(new ArrayWheelAdapter(ageList));

                dialog_info_age.findViewById(R.id.sure).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        age.setText(ageList.get(age_wheel.getCurrentItem()));
                        DialogUtil.getInstance().dialog_bottom.dismiss();
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("age", ageList.get(age_wheel.getCurrentItem()));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_USERINFO, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                            @Override
                            public void onSuccess(SendCodeBean sendCodeBean) {
                                dismissDialog();
                                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                    EventBus.getDefault().post("refresh_mine");
                                } else {
                                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                    } else {
                                        showImageToas(sendCodeBean.getMsg());
                                    }
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                dismissDialog();
                            }
                        });
                    }
                });
                dialog_info_age.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        DialogUtil.getInstance().dialog_bottom.dismiss();
                    }
                });

                break;
            case R.id.job_rl:
                finalOkGo.request(RequestType.POST, Url.GET_JOB_LIST, null, Url.GET_JOB_LIST, new Callback<JobListBean>() {
                    @Override
                    public void onSuccess(JobListBean jobListBean) {
                        if(jobListBean.getCode()== Contacts.SUCCESS){
                            DialogUtil.getInstance().showBottomDialog(context, R.layout.dialog_info_age);
                            LinearLayout dialog_info_job = (LinearLayout) DialogUtil.getInstance().dialog_bottom_layout;

                            List<String> jobList = new ArrayList<>();
                            for(int i=0;i<jobListBean.getList().size();i++){
                                jobList.add(jobListBean.getList().get(i).getName());
                            }
                            MyWheelView job_wheel = dialog_info_job.findViewById(R.id.age_wheel);
                            job_wheel.setCyclic(false);
                            job_wheel.setTextSize(21);
                            job_wheel.setItemsVisibleCount(5);
                            job_wheel.setLineSpacingMultiplier(2);
                            job_wheel.setAdapter(new ArrayWheelAdapter(jobList));

                            dialog_info_job.findViewById(R.id.sure).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    job.setText(jobList.get(job_wheel.getCurrentItem()));
                                    DialogUtil.getInstance().dialog_bottom.dismiss();
                                    JSONObject jsonObject = new JSONObject();
                                    try {
                                        jsonObject.put("occupation", jobList.get(job_wheel.getCurrentItem()));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_USERINFO, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                        @Override
                                        public void onSuccess(SendCodeBean sendCodeBean) {
                                            dismissDialog();
                                            if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                                EventBus.getDefault().post("refresh_mine");
                                            } else {
                                                if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                                } else {
                                                    showImageToas(sendCodeBean.getMsg());
                                                }
                                            }
                                        }

                                        @Override
                                        public void onError(Response<String> response) {
                                            super.onError(response);
                                            dismissDialog();
                                        }
                                    });
                                }
                            });
                            dialog_info_job.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    DialogUtil.getInstance().dialog_bottom.dismiss();
                                }
                            });
                        }else{
                            showImageToas(jobListBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }
}
